package client;

import database.BeePool;
import tools.FileoutputUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicLong;

public class MapleEquipOnlyId {
    private AtomicLong runningId;

    public static MapleEquipOnlyId getInstance() {
        return SingletonHolder.instance;
    }

    private MapleEquipOnlyId() {
        this.runningId = new AtomicLong(0L);
    }

    public long getNextEquipOnlyId() {
        if (this.runningId.get() <= 0L) {
            this.runningId.set(this.initOnlyId());
        } else {
            this.runningId.set(this.runningId.get() + 1L);
        }
        return this.runningId.get();
    }

    public long initOnlyId() {
        long ret = 0L;
        try (PreparedStatement ps = BeePool.getConnection().prepareStatement("SELECT MAX(equipOnlyId) FROM inventoryitems WHERE equipOnlyId > 0");
             ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                ret = (long) (rs.getInt(1) + 1);
            }
            ps.close();
            rs.close();
        } catch (SQLException e) {
            FileoutputUtil.outError("logs/资料库异常.txt", (Throwable) e);
            e.printStackTrace();
        }
        return ret;
    }

    private static class SingletonHolder {
        protected static MapleEquipOnlyId instance;

        static {
            instance = new MapleEquipOnlyId();
        }
    }
}
